package com.room.search.service;

import com.room.search.constant.Constants;
import com.room.search.constant.HttpStatus;
import com.room.search.domain.RoomCommunity;
import com.room.search.domain.RoomFile;
import com.room.search.domain.enumeration.file.FileType;
import com.room.search.domain.enumeration.file.ImageType;
import com.room.search.repository.RoomCommunityRepository;
import com.room.search.repository.RoomFileRepository;
import com.room.search.repository.RoomGoodsRepository;
import com.room.search.response.RoomResult;
import com.room.search.service.dto.RoomFIleOutPutDTO;
import com.room.search.util.FastDfsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Optional;

/**
 * Service Implementation for managing {@link RoomFile}.
 */
@Service
@Transactional
public class RoomFileService {

    private final Logger log = LoggerFactory.getLogger(RoomFileService.class);
    private static final String PREFIX = Constants.IMAGE;


    private final RoomFileRepository roomFileRepository;
    private final RoomCommunityRepository roomCommunityRepository;
    private final RoomGoodsRepository roomGoodsRepository;

    public RoomFileService(RoomFileRepository roomFileRepository,
                           RoomCommunityRepository roomCommunityRepository,
                           RoomGoodsRepository roomGoodsRepository) {
        this.roomFileRepository = roomFileRepository;
        this.roomCommunityRepository = roomCommunityRepository;
        this.roomGoodsRepository = roomGoodsRepository;
    }

    /**
     * 图片上传
     */
    public RoomResult imageUpload(Long id, MultipartFile file, ImageType type) {
        log.info("上传的图片：{}", file);
        if (file.isEmpty()) {
            return RoomResult.error("请选择图片上传");
        }

        String filename = file.getOriginalFilename();

        if (filename == null) {
            return RoomResult.error("文件名不能为空");
        }
        String ext = filename.substring(filename.lastIndexOf(".")+1);
        String[] upload = FastDfsUtils.upload(file);

        if (upload == null) {
            return RoomResult.error("上传文件失败");
        }

        if (type.equals(ImageType.COMMUNITY)) {
            return roomCommunityRepository.findById(id)
                .map(community -> {

                    if (!CollectionUtils.isEmpty(roomFileRepository.findAllByCommunityAndFileName(community, filename))) {
                        return RoomResult.error("该小区已经有该照片");
                    }

                    RoomFile roomFile = new RoomFile()
                        .fileName(filename)
                        .fileType(FileType.JPG)
                        .fileExt(ext)
                        .imageType(type)
                        .fileRemark(community.getName())
                        .fileGroup(upload[0])
                        .filePath(upload[1])
                        .setCommunity(community)
                        .setFileUrl(PREFIX + upload[0] + "/" + upload[1]);

                    roomFileRepository.save(roomFile);
                    return RoomResult.success(roomFile);
                }).orElseGet(() -> RoomResult.error("无该小区记录"));
        }

        return roomGoodsRepository.findById(id)
            .map(roomGoods -> {
                if (!CollectionUtils.isEmpty(roomFileRepository.findAllByGoodsAndFileName(roomGoods, filename))) {
                    return RoomResult.error("该房产已经有该照片");
                }
                RoomResult success = RoomResult.success("上传图片成功");

                RoomFile roomFile = new RoomFile()
                    .fileName(filename)
                    .fileType(FileType.JPG)
                    .fileExt(ext)
                    .imageType(type)
                    .fileRemark(roomGoods.getBkNo())
                    .fileGroup(upload[0])
                    .filePath(upload[1])
                    .setGoods(roomGoods)
                    .setFileUrl(PREFIX + upload[0] + "/" + upload[1]);
                roomFileRepository.save(roomFile);
                success.put("data", roomFile);
                return success;
            }).orElseGet(() -> RoomResult.error("无该处房产记录"));

    }

    /**
     * 下载文件
     */
    public ResponseEntity<Byte[]> downloadFile(Long id) {
        RoomFile file = roomFileRepository.findById(id).orElse(null);
        log.info("下载的文件：{}", file);
        if (file == null) {
            return ResponseEntity.status(HttpStatus.ERROR).body(null);
        }
        return null;
    }

    /**
     * 删除文件
     */
    public RoomResult deleteFile(Long id) {
        roomFileRepository.deleteById(id);
        return RoomResult.success("删除成功");
    }


    public RoomResult getFileByCommunity(Long id) {
        RoomCommunity community = roomCommunityRepository.findById(id).orElse(null);
        if (community == null) {
            return RoomResult.error("无此小区");
        }
        List<RoomFile> roomFiles = roomFileRepository.findAllByCommunity(community);
        return RoomResult.success(roomFiles);
    }

    public RoomResult getFileByGoods(Long id) {
        return roomGoodsRepository.findById(id)
            .map(roomGoods -> RoomResult.success(roomFileRepository.findAllByGoods(roomGoods)))
            .orElseGet( ()-> RoomResult.error("无该房源"));
    }

    public String getFileName(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        return file.getOriginalFilename();
    }

    /**
     * 上次文件接口
     */
    public RoomResult upload(MultipartFile file) {
        String fileName = getFileName(file);
        if (fileName == null) {
            return RoomResult.error("文件格式错误");
        }
        //后缀名
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        String[] upload = FastDfsUtils.upload(file);

        if (upload == null) {
            return RoomResult.error("上传文件失败");
        }

        String url = PREFIX + upload[0] + "/" + upload[1];

        RoomFile roomFile = roomFileRepository.findAllByFileUrl(url).orElse(new RoomFile());


        roomFile
            .fileName(fileName)
            .fileType(FileType.getTypeByExtension(ext))
            .fileExt(ext)
            .fileRemark(fileName)
            .fileGroup(upload[0])
            .filePath(upload[1])
            .setFileUrl(PREFIX + upload[0] + "/" + upload[1]);

        roomFileRepository.save(roomFile);
        RoomFIleOutPutDTO data = new RoomFIleOutPutDTO();
        data.setName(fileName)
            .setUrl(url);

        return RoomResult.success("上传成功", data);
    }
}
